<!-- 例子：
<pb-form-extend ref="formExtend" :initModel="initModel" v-if="formConfigData" :formConfigData="formConfigData" :readOnly="false"></pb-form-extend>

表单默认值填充（空表单initModel可不传）
initModel: {
	"phone":"13328301234",
	"advice":"我是建议"
},
formConfigData: {
	"list": [{
			"column": "phone",//后台保存该题目答案的字段
			"label": "手机号码",//题目
			"title": "手机号码",//题目回显
			"type": "input",//input、textarea、radio、checkbox、date
			"placeholder": "请输入手机号码",
			"disabled": false,
			"enable": true,
			"rule": {
				"type": "string",
				"required": true,
				"message": "请输入有效手机号码",
				"trigger": ["blur"],//blur:失去焦点 change:值改变
				"control": {
					"ruleSelf": "mobile",//本题规则验证mobile、email、idCard、carNo
					"否": {
						"operationType": {
							"disabled": true,
							"required": false,
							"value": "none"
						}
					},
					"是": {
						"operationType": {
							"disabled": false,
							"required": true
						}
					}
				}
			}
		}]
}

console.log('model===' + JSON.stringify(this.$refs.formExtend.model))
this.$refs.formExtend.validate().then(res => {
	//...提交表单
}).catch(e => {
	uni.showToast({
		icon: "none",
		title: "表单验证未通过，请认真填写表单信息。"
	})
}) 
-->


<template>
	<view>
		<u--form v-if="model && readOnly == false" labelPosition="top" :model="model" :labelStyle="labelStyle"
			:rules="rules" ref="uForm">
			<view class="form" v-for="(obj,index) in list" :key="index">

				<u-form-item labelWidth="100%" :required="isShowrequired(obj)" :prop="obj.column" :label="(index+1)+'、'+obj.label" :borderBottom="false"
					ref="item1">

					<template v-if="obj.type=='radio'">
						<u-radio-group :disabled="obj.disabled" v-model="model[obj.column]" placement="column">
							<u-radio :customStyle="{marginBottom: '24rpx'}" :labelSize="itemLabelFontSize"
								:labelColor="itemLabelColor" v-for="(item, subIndex) in obj.items" :key="subIndex"
								:label="item.name" :name="item.name">
							</u-radio>
						</u-radio-group>
					</template>

					<template v-else-if="obj.type=='checkbox'">
						<u-checkbox-group :disabled="obj.disabled" v-model="model[obj.column]" placement="column">
							<u-checkbox :customStyle="{marginBottom: '24rpx'}" :labelSize="itemLabelFontSize"
								:labelColor="itemLabelColor" v-for="(item, subIndex) in obj.items" :key="subIndex"
								:label="item.name" :name="item.name">
							</u-checkbox>
						</u-checkbox-group>
					</template>

					<template v-else-if="obj.type=='date'">
						<pb-picker-date :ref="'datePicker'+obj.column" mode="date" :date="model[obj.column]"
							:identity="obj.column" @updateDate="updateDate" :title="obj.label"></pb-picker-date>
						<view style="width: 100%;"
							class="pb-flex-row pb-cross-center pb-main-between text-content"
							@click="$refs['datePicker'+obj.column][0].show = true">
							<u-input readonly v-model="model[obj.column]" :fontSize="itemLabelFontSize"
								:color="itemLabelColor" placeholder="请输入日期" border="none"></u-input>
							<u-icon name="arrow-right" color="#C4C4C4" size="32rpx"></u-icon>
						</view>
					</template>

					<template v-else-if="obj.type == 'input'">
						<u-input v-model="model[obj.column]" :fontSize="itemLabelFontSize" :color="itemLabelColor"
							:placeholder="obj.placeholder?obj.placeholder:'请输入'" border="surround"></u-input>
					</template>
					
					<template v-else-if="obj.type == 'textarea'">
						<u--textarea v-model="model[obj.column]" :fontSize="itemLabelFontSize" :color="itemLabelColor" :placeholder="obj.placeholder?obj.placeholder:'请输入'" border="surround" count maxlength="150" height="160rpx"></u--textarea>
					</template>	

				</u-form-item>

			</view>

		</u--form>

		<template v-if="readOnly == true">
			<view v-for="(obj,index) in list" :key="index">
				<view v-if="showColumValue(obj)" class="pb-flex-row item-label">
					<text class="text-label-mini"
						:style="'flex-shrink: 0;font-size: '+titleFontSize+';'">{{obj.title || obj.label}}：</text>
					<text class="text-content-mini"
						:style="'font-size: '+itemLabelFontSize+';'">{{showColumValue(obj)}}</text>
				</view>
			</view>

		</template>
	</view>
</template>

<script>
	export default {
		name: "pb-form-extend",
		props: {
			formConfigData: {
				type: Object,
				default: () => {},
				require: true
			},
			initModel: {
				type: Object,
				default: () => {}
			},
			diseaseKey: {
				type: String,
				require: true,
			},
			readOnly: {
				type: Boolean,
				default: false,
			},
			titleFontSize: {
				type: String,
				default: '32rpx',
			},
			titleColor: {
				type: String,
				default: '#4C4C4C',
			},
			itemLabelFontSize: {
				type: String,
				default: '32rpx',
			},
			itemLabelColor: {
				type: String,
				default: '#4C4C4C',
			}
		},
		data() {
			return {
				model: null,
				list: null,
				rules: null,
				labelStyle: {
					"color": "#4C4C4C",
					"font-size": "32rpx",
				}
			};
		},
		options: {
			styleIsolation: 'shared' // 解除样式隔离(解决在子组件中使用deep修改第三方样式失效的问题)
		},
		created() {
			
			this.labelStyle['font-size'] = this.titleFontSize
			this.labelStyle.color = this.titleColor
			
			let formList = this.formConfigData.list || []
			let tempModel = {}
			let tempList = []
			let tempRules = {}
			formList.forEach(item => {
				if (item.enable == true && this.hasMenuByDiseaseKey(item)) {
					//题目赋值（list）
					if (item.items && item.items.length > 0) {
						item.items.forEach(subItem => {
							if (subItem.name) {
								subItem.name = subItem.name.replace(/&gt;/gm, '>')
								subItem.name = subItem.name.replace(/&lt;/gm, '<')
							}
						})
					}
					tempList.push(item)
					
					//数据模型属性初始化（model）
					if (item.type == 'checkbox') {
						tempModel[item.column] = []
					} else {
						tempModel[item.column] = ''
					}
					
					//规则赋值
					if(item.rule) {
						tempRules[item.column] = item.rule
					}
				}
			})

			this.list = tempList
			this.model = tempModel
			if (this.initModel) {
				let initModelKeys = Object.keys(this.initModel)
				if (initModelKeys && initModelKeys.length > 0) {
					initModelKeys.forEach(key => {
						if (this.initModel[key]) {
							if (Object.prototype.toString.call(this.initModel[key]) === '[object Array]') {
								this.initModel[key] = JSON.parse(JSON.stringify(this.initModel[key]).replace(
									/&gt;/gm, '>'))
								this.initModel[key] = JSON.parse(JSON.stringify(this.initModel[key]).replace(
									/&lt;/gm, '<'))
							} else if(Object.prototype.toString.call(this.initModel[key]) === '[object String]')  {
								this.initModel[key] = this.initModel[key].replace(/&gt;/gm, '>')
								this.initModel[key] = this.initModel[key].replace(/&lt;/gm, '<')
							}
						}
					})
				}
				this.model = uni.$u.deepMerge(this.model, this.initModel)
			}

			delete tempRules['@type']
			let tempRulesKeys = Object.keys(tempRules)
			tempRulesKeys.forEach(column => {
				let ruleObj = tempRules[column]
				if (ruleObj.control) {
					ruleObj['validator'] = (rule, value, callback) => {
						//自身值有效性校验
						if (ruleObj.control.ruleSelf && value) {
							if (ruleObj.control.ruleSelf == 'mobile') {
								//手机号码验证
								return uni.$u.test.mobile(value)
							} else if (ruleObj.control.ruleSelf == 'email') {
								//邮箱验证
								return uni.$u.test.email(value)
							} else if (ruleObj.control.ruleSelf == 'idCard') {
								//身份证号码验证
								return uni.$u.test.idCard(value)
							} else if (ruleObj.control.ruleSelf == 'carNo') {
								//车牌号码验证
								return uni.$u.test.carNo(value)
							}
						}

						//联动至其他选项配置
						if (ruleObj.control[value]) {
							delete ruleObj.control[value]['@type']
							this.ruleControlHandle(tempRules, ruleObj.control[value])
						}

						//必填项校验
						if (rule.required == true && (value == '' || value == null || value == undefined)) {
							return false
						}
						return true
					}

					//如果model已经是有值的，需要调用一次规则控制处理
					if (this.model && this.model[column]) {
						this.ruleControlHandle(tempRules, ruleObj.control[this.model[column]])
					}
				}
			})
			this.rules = tempRules
			// console.log('【form-extend】model=>' + JSON.stringify(this.model))
			// console.log('【form-extend】list=>' + JSON.stringify(this.list))
			// console.log('【form-extend】rules=>' + JSON.stringify(this.rules))
			this.$nextTick(() => {
				if (this.readOnly == false) {
					this.$refs.uForm.setRules(this.rules)
				}
			})
		},
		watch: {
			initModel(newInitModel) {
				if (newInitModel) {
					let initModelKeys = Object.keys(newInitModel)
					if (initModelKeys && initModelKeys.length > 0) {
						initModelKeys.forEach(key => {
							if (newInitModel[key]) {
								if (Object.prototype.toString.call(newInitModel[key]) === '[object Array]') {
									newInitModel[key] = JSON.parse(JSON.stringify(newInitModel[key]).replace(
										/&gt;/gm, '>'))
									newInitModel[key] = JSON.parse(JSON.stringify(newInitModel[key]).replace(
										/&lt;/gm, '<'))
								} else if(Object.prototype.toString.call(this.initModel[key]) === '[object String]')  {
									newInitModel[key] = newInitModel[key].replace(/&gt;/gm, '>')
									newInitModel[key] = newInitModel[key].replace(/&lt;/gm, '<')
								}
							}
						})
					}
					this.model = newInitModel
				}
			},
			readOnly(newValue) {
				this.$nextTick(() => {
					if (this.readOnly == false) {
						this.$refs.uForm.setRules(this.rules)
					}
				})
			}
		},
		methods: {
			//根据病种过滤菜单
			hasMenuByDiseaseKey(item) {
				//1、筛选通用菜单
				if(item.diseaseKeys && item.diseaseKeys.list && item.diseaseKeys.list.length > 0) {
					//1.1、非通用菜单
					if (this.diseaseKey) {
						if (item.diseaseKeys.list.includes(this.diseaseKey)) {
							return true
						}
					}
					return false
				}else {
					//1.2、通用菜单
					if(item.excludeDiseaseKeys && item.excludeDiseaseKeys.list && item.excludeDiseaseKeys.list.length > 0) {
						//1.2.1、通用菜单中排除的病种（被排除的病种不显示该通用菜单）
						if (this.diseaseKey) {
							if (item.excludeDiseaseKeys.list.includes(this.diseaseKey)) {
								return false
							}
						}
					}
					return true
				}
			},
			//tempRules所有的规则对象，modifyItems需要被修改的项目
			ruleControlHandle(tempRules, modifyItems) {
				let itemKeys = Object.keys(modifyItems)
				if (itemKeys) {
					itemKeys.forEach(itemKey => {
						let item = this.list.find(item => item.column == itemKey)
						if (item) {
							let modifyItem = modifyItems[itemKey]
							delete modifyItem['@type']
							let itemPropertyKeys = Object.keys(modifyItem)
							if (itemPropertyKeys) {
								itemPropertyKeys.forEach(itemPropertyKey => {
									if (itemPropertyKey == 'value' && modifyItem.value == 'none') {
										//value属性特殊处理一下
										this.model[item.column] = ''
									} else if (itemPropertyKey == 'required' &&
										modifyItem.required != null && modifyItem
										.required != undefined) {
										//required属性特殊处理一下
										tempRules[itemKey].required = modifyItem.required
										console.log(
											`【form-extend】column=${itemKey}->required=${modifyItem.required}`
											)
									} else {
										item[itemPropertyKey] = modifyItem[itemPropertyKey]
										console.log(
											`【form-extend】column=${itemKey}->${itemPropertyKey}=${modifyItem[itemPropertyKey]}`
											)
									}

								})
							}

						}
					})

				}

			},
			updateDate(date, identity) {
				this.model[identity] = date
				this.$forceUpdate()
			},
			validate() {
				return this.$refs.uForm.validate()
			},
			showColumValue(obj) {
				if (Object.prototype.toString.call(this.model[obj.column]) === '[object Array]') {
					return this.model[obj.column].join('、')
				}
				return this.model[obj.column]
			},
			isShowrequired(obj) {
				if (obj.rule && (obj.rule.required!=null || obj.rule.required!=undefined || obj.rule.required != '')) {
					return obj.rule.required
				}
				return false
			}
		}
	}
</script>

<style lang="scss" scoped>
	.form {
		background-color: white;
		padding: 0 32rpx;
		margin-bottom: 20rpx;
	}
	
	.item-label {
		padding: 0rpx 24rpx 12rpx 24rpx;
	}
	
	// 错误信息样式修改
	/* #ifndef VUE3 */
	/deep/.u-form-item__body__right__message {
		margin-bottom: 24rpx;
		font-size: 24rpx;
	}
	/* #endif */
	
	/* #ifdef VUE3 */
	:deep(.u-form-item__body__right__message) {
		margin-bottom: 24rpx;
		font-size: 24rpx;
	}
	/* #endif */
	
</style>